use axum_app_macro::QueryPageBuilder;
use sea_orm::*;

use crate::entity::sys_resource::*;

#[derive(Debug, QueryPageBuilder)]
pub struct ResourceQuery;

impl ResourceQuery {
    pub async fn find_resource_by_id(db: &DbConn, id: u64) -> Result<Option<Model>, DbErr> {
        Entity::find_by_id(id as i64).one(db).await
    }

    pub async fn find_resource_by_code(db: &DbConn, code: String) -> Result<Option<Model>, DbErr> {
        Entity::find()
            .filter(Column::ResCode.eq(code))
            .filter(Column::DeleteFlag.eq(0u64))
            .one(db)
            .await
    }
}

pub async fn insert_resource<C>(db: &C, sys_resource: ActiveModel) -> Result<u64, DbErr>
where
    C: ConnectionTrait,
{
    let res = Entity::insert(sys_resource).exec(db).await;
    let res = res.map(|res| res.last_insert_id as u64);

    res
}

#[cfg(test)]
mod tests {
    use axum_app_common::test::get_connect;
    use sea_orm::{DbConn, Order};

    use crate::{
        entity::sys_resource::{self, Column},
        resource_dal::{insert_resource, ResourceQueryCondition},
        ResourceQuery,
    };

    #[tokio::test]
    async fn test_insert_resource() {
        let db = get_connect().await;

        let model = sys_resource::ActiveModel {
            res_code: sea_orm::ActiveValue::Set("user.query.page".to_string()),
            res_name: sea_orm::ActiveValue::Set("用户信息分页查询".to_string()),
            res_description: sea_orm::ActiveValue::Set("用户信息分页查询".to_string()),
            res_type: sea_orm::ActiveValue::Set("service".to_string()),
            ..sys_resource::ActiveModel::default()
        };

        let res = insert_resource(&db, model).await;

        match res {
            Ok(id) => println!("插入数据ID={id}"),
            Err(err) => {
                let msg =
                    axum_app_common::error::parse_db_err_duplicate_err(err.to_string().as_str())
                        .unwrap_or(("".to_string(), "数据重复".to_string()));
                println!("err:{:?}", msg);
            }
        }

        let res = ResourceQuery::query_page(
            &db,
            1u64,
            20u64,
            ResourceQueryCondition::new(vec![(Column::Id, Order::Asc)]),
        )
        .await;

        println!("page query res: {:?}", res);
    }
}
